<template>
  <div
      class="chatting flex flex-col flex-1 bg-white pt-[20px] w-full min-w-0"
  >
    <!--对话框-->
    <div class="flex-1 flex flex-col min-h-0">
      <div v-if="title" class="text-center">{{ title }}</div>
      <el-scrollbar ref="scrollbarRef" height="100%" @scroll="scroll">
        <slot></slot>
        <div ref="innerRef" class="contentList">
          <div
              class="px-[40px] pb-[40px]"
              v-if="!contentList.length && modelInfo.tips"
          >
            <div class="message-contain message--his">
              <ChatMsgItem
                  v-if="chatType != 0"
                  :type="2"
                  :is-collet="0"
                  :avatar="avatar"
                  :show-collect-btn="false"
                  :show-copy-btn="false"
                  :show-poster="false"
                  :is_member_download="props.is_member_download"
              >
                <template #rob>
                  <chat-content :content="modelInfo.tips" />
                </template>
              </ChatMsgItem>
            </div>
          </div>
          <div
              v-for="(item, index) in contentList"
              :key="index"
              class="px-[40px] pb-[40px]"
          >
            <!-- <div
                class="text-center text-info"
                v-if="timeFormat(item, index)"
            ></div> -->
            <!-- rob message -->
            <div
                class="message-contain message--his"
                v-if="item.type === 2"
            >

              <ChatMsgItem
                  :avatar="avatar"
                  :type="2"
                  :loading="item.loading"
                  :stopping="!!item.content"
                  :show-rewrite-btn="
                                    index === contentList.length - 1
                                "
                  :time="item.create_time"
                  :model-name="model_name"
                  :is-collet="item.is_collect"
                  :record-id="item.id"
                  :is_member_download="props.is_member_download"


              >
                <template #rob>
                  <template
                      v-if="
                                            item.loading && !item.content.length
                                        "
                  >
                    <div class="text-primary">
                      创作思考中...
                    </div>
                  </template>
                  <div
                      v-for="(text, index) in item.content"
                      :key="index"
                      class="mb-[15px] last-of-type:mb-0"
                      :class="{
                                            'pt-[15px] border-t border-solid border-br-light':
                                                index > 0
                                        }"
                  >
                    <chat-content
                        :loading="item.loading"
                        :content="text"
                        :strs="extractMermaidCode(text)"
                        :binary_data_base64="item.binary_data_base64"
                        :use-markdown="
                                                !!appStore.config?.chat
                                                    ?.is_markdown
                                            "
                        :index="index"
                        :show-rewrite-btn="index === item.content.length - 1"
                        :record-id="item.id"
                        :show-copy-btn="!item.loading"
                        :show-voice-btn="
                                                !item.loading &&
                                                appStore.getIsVoiceOpen
                                            "
                        :types="item.type"
                        @copy="copyContent(text)"
                        @collect="collect(item.id, item)"
                        @copy-content="copyContent(item.content)"
                        @close="emit('close', index)"
                        @poster="handleDrawPoster(item.id)"
                        :model_id="props.currentId"
                        @rewrite="rewrite"
                        @wodrs="wodrs(item.id)"
                        @addppt="addppt(item.id)"
                        :is_member_download="props.is_member_download"
                    />
                  </div>
                </template>
              </ChatMsgItem>
            </div>
            <!--my msg-->
            <div>
              <div
                  class="message-contain message--my"
                  v-if="item.type === 1"
              >
                <ChatMsgItem
                    :avatar="item.from_avatar"
                    :type="1"
                    :show-poster="false"
                    @copy-my-content="copyContent(item.content)"
                >
                  <template #my>

                    <chat-content
                        :is_member_download="props.is_member_download"

                        :content="item.content"
                        :file="{
                                                url: item.file_url,
                                                name: item.file_name,
                                                type: item.file_type
                                            }"
                    />
                  </template>
                </ChatMsgItem>
              </div>
            </div>

            <!--    上下文被清除    -->
            <div
                v-if="item.new_chat && item.type === 2"
                class="clean-context flex justify-center items-center"
            >
              - 已清除上下文关联，开始全新的会话 -
            </div>
          </div>
        </div>
      </el-scrollbar>
    </div>

    <div class="lg:px-[26px] mx-[10px]">
      <div
          v-if="contentList.length"
          class="flex-1 flex justify-center items-center"
      >
        <ElButton
            v-if="!props.sendDisabled"
            color="#f6f6f6"
            :round="true"
            style="--el-button-disabled-text-color: #999"
            @click="emit('contentPost', '继续', 1,'继续')"
        >
          <Icon name="el-icon-VideoPlay" :size="18" />
          <span class="ml-[5px]">继续</span>
        </ElButton>
        <ElButton
            v-else
            color="#f6f6f6"
            :round="true"
            style="--el-button-disabled-text-color: #999"
            @click="emit('close')"
        >
          <Icon name="el-icon-VideoPause" :size="18" />
          <span class="ml-[5px]">停止</span>
        </ElButton>
      </div>

      <div v-if="isShowFileUpload" class="max-w-[400px]">
        <upload-file
            v-model="chatPlugin.file"
            :accept="getFileExtname"
            :type="chatPlugin.type"
            :list-type="chatPlugin.type == 'image' ? 'picture' : 'text'"
            :data="{
                        type: chatPlugin.type == 'file' ? 'docs' : '',
                        key: chatPlugin.type != 'image' ? chatPlugin.id : ''
                    }"
        >
          <el-button
              class="!bg-white !text-primary"
              type="primary"
              plain
          >
            <template #icon>
              <Icon name="el-icon-Upload" />
            </template>
            {{
              chatPlugin.type == 'image' ? '上传图片' : '上传文件'
            }}
          </el-button>
        </upload-file>
      </div>
      <div class="flex items-center">

        <div class="flex border11 cz" @click="cleanChatLog">
          <Icon name="el-icon-ChatDotRound"/>
          <div>新建创作</div>
        </div>
        <div class="flex border11" @click="lishing">
          <Icon name="el-icon-Clock" />
          <div>创作记录</div>
        </div>

        <div class="flex border11" @click="getexampleplList()" v-if="is_open_batch == 1 && !is_submit">
          <Icon name="el-icon-QuestionFilled" />
          <div>批量任务记录</div>
        </div>
        <!--<div class="flex border11" @click="getexampleList()">
          <Icon name="el-icon-QuestionFilled" />
          <div>问题模板</div>
        </div>-->
       <!-- <div class="flex border11" @click="tiwen">
          <Icon name="el-icon-Tickets" />
          <div>提问表单</div>
        </div>-->

        <!--插件选择-->
        <!--<Plugins
            v-if="chatType == 1"
            v-model="chatPlugin.id"
            @update:model-value="pluginChange"
            class="py-[10px]"
        />-->
        <!--模型选择-->
        <!--<ModelPicker
            class="mr-[10px]"
            v-show="!chatPlugin.id"
            v-model="chatModel"
        />-->
        <!--联网开关-->
        <!--<NetworkSwitch
            v-model="chatNetwork"
            class="my-[10px]"
            v-if="!chatPlugin.id"
        />-->
        <!--清除上下文-->
        <ElButton
            v-if="chatType === 3"
            class="flex items-center ml-1"
            :link="true"
            @click="emit('clearContext')"
        >
          <Icon name="local-icon-context" color="inherit" :size="14" />
          <span class="ml-1 mt-[3px]">清除上下文关联</span>
        </ElButton>
      </div>

      <!--输入框-->
      <div class="flex items-end">
        <div
            class="flex h-full items-end flex-1 rounded-sm overflow-hidden"
        >
          <ElInput
              v-model="inputContent"
              :input-style="{
                            backgroundColor: '#F8F8FB'
                        }"
              :class="[
                            'min-h-full py-[4px] content',
                            { 'content-focus': isFocus }
                        ]"
              placeholder="请输入内容（Shift + Enter）= 换行"
              type="textarea"
              :autosize="{
                            maxRows: 4
                        }"
              resize="none"
              @focus="isFocus = true"
              @blur="isFocus = false"
              @compositionstart="isInputChinese = true"
              @compositionend="isInputChinese = false"
              @keydown="handleInputEnter"
              @click="handleClick"
          />
        </div>
        <ElButton
            class="ml-2"
            type="primary"
            @click="contentPost"
            size="large"
            :disabled="props.sendDisabled"
        >
          <template #default> 发送 </template>
        </ElButton>

      </div>

      <LayoutFooter />
    </div>
    <DialogPoster ref="posterRef" />

    <el-dialog v-model="dialogTableVisible" title="问题模板" width="800">
      <el-tabs v-model="currentTab">
        <el-tab-pane
            v-for="(item, index) in exampleList"
            :label="item.name"
            :name="index"
            :key="item.id"
        >
          <div class="h-[300px]">
            <el-scrollbar>
              <div>
                <template v-if="item.sample">
                  <div
                      v-for="sample in item.sample"
                      :key="sample.id"
                      class="sample-item mb-[20px] p-[10px] flex justify-center cursor-pointer"
                      @click="clickItem(sample.content)"
                  >
                    <div class="line-clamp-2">
                      {{ sample.content }}
                    </div>
                  </div>
                </template>
                <template v-else>
                  <div class="py-[150rpx]">
                    <u-empty
                        text="暂无数据"
                        mode="data"
                    ></u-empty>
                  </div>
                </template>
              </div>
            </el-scrollbar>
          </div>
        </el-tab-pane>
      </el-tabs>
      <div v-if="exampleList.length <= 0" style="text-align: center;">暂无问题模板</div>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import {ElInput, ElButton, ElScrollbar, ElMessageBox} from 'element-plus'
import {
  cleanChat,
  collectRecords,
  getCreationDetail,
  getSkillDetail, QusamplesLists,
  samplesLists, skillQuestionsamplesLists
} from '@/api/chat'
const router = useRouter()
import { useUserStore } from '~~/stores/user'
import feedback from '~~/utils/feedback'
import { useElementSize, useVModel } from '@vueuse/core'
import {cancelCollect, downloadWords} from '~~/api/my'
import { useAppStore } from '~/stores/app'
import DialogPoster from './dialog-poster.vue'
import ModelPicker from './model-picker.vue'
import Plugins from './plugins.vue'
import { CHAT_MODEL_KEY } from '~/enums/cacheEnums'
import LayoutFooter from '~/layouts/components/footer/index.vue'
const appStore = useAppStore()
const userStore = useUserStore()



const gridData = [
  {
    date: '2016-05-02',
    name: 'John Smith',
    address: 'No.1518,  Jinshajiang Road, Putuo District',
  }]
const { isLogin, toggleShowLogin } = userStore
const posterRef = shallowRef()
const emit = defineEmits([
  'loading',
  'contentPost',
  'cleanChatLog',
  'clearContext',
  'close',
  'update:model',
  'update:network',
  'update:plugin',
  'top'
])

const dialogTableVisible = ref(false)
const dialogTableVisible1 = ref(false)
const props = defineProps({
  contentList: {
    type: Array as any,
    default: () => []
  },
  selectval: {
    type: [String, Number],
    default: ''
  },
  chatType: {
    type: Number,
    default: 0
  },
  model_id:{
    type: Number,
    default: 0
  },
  model_name: {
    type: String,
    default: ''
  },
  title: {
    type: String,
    default: ''
  },
  sendDisabled: {
    type: Boolean
  },
  avatar: {
    type: String
  },
  is_member_download:{
    type: String
  },
  is_open_batch:{
    type: String
  },
  model: {
    type: String
  },
  network: {
    type: Boolean
  },
  is_submit:{
    type: Boolean
  },
  currentId: {
    type: Number,
    default: 0
  },
  plugin: {
    type: Object,
    default: () => ({})
  }
})
const exampleList = ref([])
function getexampleList(){
  if (props.sendDisabled) return
  QusamplesLists({ model_id: props.currentId }).then(res => {
    exampleList.value = res
    dialogTableVisible.value = true
  })
}

const currentTab = ref(0)
const isFocus = ref(false)
//输入框输入内容.
const inputContent = ref('')
//对话框ref
const innerRef = ref<HTMLDivElement>(null)

//滚动条ref
const scrollbarRef = ref<InstanceType<typeof ElScrollbar>>(null)




const clickItem = (value: string) => {
  dialogTableVisible.value = false
  inputContent.value = value
}

const lishing = (value: string) => {
  if (props.sendDisabled) return
  emit('addMsg')
}

const getexampleplList =  (value: string) => {
  emit('plMsg',props.model_id)
}

const tiwen = (value: string) => {
  emit('addFrom')
}

const xinjian = (value: string) => {
  emit('addMsg')
}

// 聊天模型
const chatModel = useVModel(props, 'model', emit)
const chatNetwork = useVModel(props, 'network', emit)
const chatPlugin = useVModel(props, 'plugin', emit)

const pluginChange = (value: string) => {
  if (value === 'xinghuo-chatdoc') {
    chatPlugin.value.type = 'file'
  } else if (value === 'gpt-4-all') {
    chatPlugin.value.type = 'image'
  } else if (value === 'kimi-chatdoc') {
    chatPlugin.value.type = 'file'
  } else {
    chatPlugin.value.type = ''
  }
  chatPlugin.value.file = {}
}

const getFileExtname = computed(() => {
  switch (chatPlugin.value.type) {
    case 'image':
      return '.jpg,.png,.gif,.jpeg'
    default:
      return '.doc,.docx,.pdf,.md,.txt'
  }
})

const isShowFileUpload = computed(() => {
  return (
      chatPlugin.value.id === 'xinghuo-chatdoc' ||
      chatPlugin.value.id === 'gpt-4-all' ||
      chatPlugin.value.id === 'kimi-chatdoc'
  )
})
//对话框滚动
const scroll = (value) => {
  refresh(value)
}

function extractMermaidCode(text) {
  const mermaidCodeRegex = /```mermaid([\s\S]*?)```/gm;
  let match;
  const mermaidCodeBlocks = [];

  while ((match = mermaidCodeRegex.exec(text))) {
    mermaidCodeBlocks.push(match[1].trim());
  }
  console.log(mermaidCodeBlocks)
  return mermaidCodeBlocks.length>0?mermaidCodeBlocks[0]:''
}

const modelInfo = ref<any>({})
const getChatModel = async () => {

  switch (props.chatType) {
    case 2:
      modelInfo.value = await getCreationDetail({
        id: props.selectval
      })
      break
    case 3:
      modelInfo.value = await getSkillDetail({
        id: props.selectval
      })
  }
}

watch(
    () => props.selectval,
    (val) => {
      if (props.chatType != 0) {
        getChatModel()
      }
    },
    {
      immediate: false
    }
)

const handleClick = () => {
  if (!isLogin) {
    toggleShowLogin()
  }
}

//点击回车键
const isInputChinese = ref(false)
const handleInputEnter = (e: any) => {
  if (e.shiftKey && e.keyCode === 13) {
    return
  }
  if (isInputChinese.value) return
  if (e.keyCode === 13) {
    contentPost()
    return e.preventDefault()
  }
}




//发送
const contentPost = () => {
  if (inputContent.value.replace(/(^\s*)|(\s*$)/g, '') == '') {
    feedback.msgError('输入为空！')
    return
  }
  // 保存聊天模型（用于刷新之后还能记住当前聊天模型
  const model = useCookie(CHAT_MODEL_KEY)
  model.value = chatModel.value

  if (props.sendDisabled) return
  if (!isLogin) {
    toggleShowLogin()
  }
  emit('contentPost', inputContent.value,1,inputContent.value)
  nextTick(() => {
    scrollToBottom()
  })
  cleanInput()
}

//清空输入框
const cleanInput = () => {
  inputContent.value = ''
}

// 设置输入
const setInput = (val: string) => {
  inputContent.value = val
}

//清空会话
const { lockFn: rewrite } = useLockFn(async () => {
  const last = props.contentList[props.contentList.length - 1]
  const userInput = props.contentList.find(({ id }) => id === last.id)

  if (userInput) {
    await cleanChat({
      type: props.chatType,
      id: last.id
    })
    // eslint-disable-next-line vue/no-mutating-props
    props.contentList.splice(props.contentList.length - 2, 2)
    console.log(userInput.content)
    return false
    emit('contentPost', userInput.content, 1)
  }
})
const cleanChatLog = () => {
  if (props.sendDisabled) return
  emit('qingkong')
  //router.push('/create')
}

//收藏会话
const collect = async (id: number, item: any) => {
  if (item.is_collect) {
    await cancelCollect({
      collect_id: item.is_collect
    })
    item.is_collect = 0
  } else {
    await collectRecords({ records_id: id })
    item.is_collect = 1
  }
}

//复制文本
const { copy } = useCopy()
const copyContent = async (content) => {
  await copy(content)
}

//计算滚动到底部高度
const toScrollHeight = () => {
  return (
      scrollbarRef.value.wrapRef.scrollHeight -
      scrollbarRef.value.wrapRef.clientHeight
  )
}

//滚动至顶部加载
const refresh = ({ scrollTop }) => {
  if (scrollTop == 0) {
    emit('top')
  }
}

const addppt = async(recordId: number) => {
  var element = document.getElementById('id_' + recordId);
  // 获取该元素的 HTML 内容
  var htmlContent = element.innerHTML;
  let str = htmlContent.replace(/uni-view/g, 'div')
  window.localStorage.setItem('ppt_str',str)
  window.localStorage.setItem('answer_id',recordId)
  router.push('/create/pptindexv1');

}

//生成wodrs
const wodrs = async(recordId: number) => {
  var element = document.getElementById('id_' + recordId);
  // 获取该元素的 HTML 内容
  var htmlContent = element.innerHTML;
  let str = htmlContent.replace(/uni-view/g, 'div')

  if((userStore.userInfo.is_member == 1 && userStore.userInfo.member_expired == 0) || props.is_member_download == 0){
    downloadWords({
      log_id: recordId,
      words:str,
      is_download:0
    }).then((res) => {
      window.location.href = res.file_url
    })
  }else{
    ElMessageBox.confirm(
        '会员专用功能，当前未开通会员',
        '对话提示',
        {
          showClose: false,
          confirmButtonText: '去开通',
          cancelButtonText: '关闭'
        }
    ).then(() => {
      // 用户点击确认，执行页面跳转
      router.push('/openvip');
    }).catch(() => {
      // 用户点击取消，执行其他逻辑（如果有需要）
    });
  }

}

const handleDrawPoster = async (recordId: number) => {
  const result = props.contentList.filter((item: any) => {
    return item.id == recordId
  })
  if (result.length != 2) {
    feedback.msgError('上下文数据不对～')
    return
  }
  posterRef.value.open({
    title: result[0].content,
    content: result[1].content
  })
}

//滚动到底部
const scrollToBottom = () => {
  const scrollH = toScrollHeight()
  scrollbarRef.value!.setScrollTop(scrollH)
}

// 滚动到指定位置
const scrollTo = (top: number) => {
  scrollbarRef.value!.setScrollTop(top)
}

const { height } = useElementSize(innerRef)
watch(height, (value) => {
  if (props.sendDisabled) {
    scrollToBottom()
  }
})

defineExpose({ scrollToBottom, scrollTo, cleanInput, setInput })
</script>
<style lang="scss" scoped>
.chatting {
  background: radial-gradient(
          farthest-side at 100% 0,
          var(--el-color-primary-light-9) 0%,
          #fff 40%
  );
}
.message-contain {
  padding: 10px 0;
}

.message--my {
  display: flex;
  justify-content: flex-end;
}

.message--his {
  display: flex;
  justify-content: flex-start;
}

.clean-context {
  margin-top: 50px;
  @apply text-tx-secondary;
}

.content {
  transition: border 0.3s;
  border-radius: 6px;
  border: 1px solid transparent;
  &-focus {
    border: 1px solid var(--el-color-primary);
  }
}
:deep(.el-textarea__inner) {
  box-shadow: none;
  background-color: var(--el-bg-color-page);
}
.border11 {
  align-items: center;
  padding: 5px;
  border-radius: 5px;
  margin-right: 20px;
  margin-bottom: 5px;
  text-align: center;
  justify-content: center;
  border: 1px solid #dfdfdf;
  font-size: 11px;
  color: #5e5757;
  cursor: pointer;
}
.cz {
  color: var(--gradient-1);
}
</style>
